using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;

namespace SensorVisual
{
    public class Ipl
    {
        private enum BitDepths : uint
        {
            IPL_DEPTH_8U = 0x00000008,    // - unsigned 8-bit integers
            IPL_DEPTH_8S = 0x80000008,    // - signed 8-bit integers
            IPL_DEPTH_16S = 0x80000010,    // - signed 16-bit integers
            IPL_DEPTH_32S = 0x80000020,    // - signed 32-bit integers
            IPL_DEPTH_32F = 0x00000020,    // - single precision floating-point numbers
            IPL_DEPTH_64F = 0x00000040     // - double precision floating-point numbers
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct IplImage
        {
            public int nSize;
            public int ID;
            public int nChannels;
            int pad11;
            public int depth;
            int pad12, pad13;
            public int dataOrder;
            public int origin;
            public int align;
            public int width;
            public int height;
            public IntPtr roi;
            IntPtr pad8, pad9, pad10;
            public int imageSize;
            public IntPtr imageData;
            public int widthStep;
            int pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
            public IntPtr imageDataOrigin;
        }

        /// <summary>
        /// Convierte una imagen en formato IplImage a Bitmap
        /// </summary>
        /// <param name="handler">Puntero a una imagen de tipo IplImage</param>
        /// <returns>Imagen de mapa de bits</returns>
        static public unsafe Bitmap IplImageToBitmap(IntPtr handler)
        {
            if (handler == IntPtr.Zero)
                return null;

            Ipl.IplImage* img = (Ipl.IplImage*)handler;

            if ((img->depth == (int)BitDepths.IPL_DEPTH_8U) && (img->nChannels == 3))
                return new Bitmap(
                    img->width,
                    img->height,
                    img->width * 3,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb,
                    img->imageData);

            return null;
        }
    }
}
